package com.badger.spring.cloud.alibaba.provider.config;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * spring mvc 增强配置
 * @author liqi
 */
@Configuration
public class WebMvcConfig {
    /**
     * 重写返回异常信息的controller
     * @param errorAttributes
     * @param serverProperties
     * @return
     */
    @Bean
    public BasicErrorController errorController(ErrorAttributes errorAttributes, ServerProperties serverProperties) {
        return new BasicErrorController(errorAttributes, serverProperties.getError()) {
            @SuppressWarnings("deprecation")
            @RequestMapping
            @Override
            public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
                Map<String, Object> body = getErrorAttributes(request, isIncludeStackTrace(request, null));
                HttpStatus status = getStatus(request);
                body.put("val", status.getReasonPhrase());
                return new ResponseEntity<>(body, status);
            }
        };
    }

}
